package com.ricchieri.lazymodel;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.filter.EmailTemplateFilter;
import com.ricchieri.model.EmailTemplate;
import com.ricchieri.service.interf.IEmailTemplateService;

public class EmailTemplateLazyDataModel extends LazyDataModel<EmailTemplate> {

	private static final long serialVersionUID = 4593253494642335825L;

	private List<EmailTemplate> emailTemplates;
	private IEmailTemplateService emailTemplateService;
	private EmailTemplateFilter emailTemplateFilter;
	
	public EmailTemplateLazyDataModel(IEmailTemplateService emailTemplateService, EmailTemplateFilter emailTemplateFilter) {
		super();
		this.emailTemplateFilter = emailTemplateFilter;
		this.emailTemplateService = emailTemplateService;
	}
	
    @Override
    public Object getRowKey(EmailTemplate emailTemplate) {
        return emailTemplate.getId();
    }

    @Override
    public EmailTemplate getRowData(String emailTemplateId) {
        int id = Integer.valueOf(emailTemplateId);

        for (EmailTemplate emailTemplate : emailTemplates) {
            if(id == emailTemplate.getId()) {
                return emailTemplate;
            }
        }
        return null;
    }
    
	@Override
	public List<EmailTemplate> load(int startingAt, int maxPerPage, String sortField, 
			SortOrder sortOrder, Map<String, String> filters) {
		
		emailTemplateFilter.setSortField(sortField);
		emailTemplateFilter.setSortOrder(sortOrder.toString());
		
        if(getRowCount() <= 0) {
            setRowCount(getEmailTemplateService().getAllEmailTemplatePaginatedCountByFilter(emailTemplateFilter));
        }
        
        if(getRowCount() == startingAt && getRowCount()  != 0) {
        	startingAt = startingAt - BusinessSettings.ROW_MAX_RESULT;
        }
        emailTemplates = getEmailTemplateService().getAllEmailTemplatePaginatedByFilter(emailTemplateFilter, startingAt);

        setPageSize(BusinessSettings.ROW_MAX_RESULT);
        
        return emailTemplates;
	}

	public List<EmailTemplate> getEmailTemplates() {
		return emailTemplates;
	}

	public void setEmailTemplates(List<EmailTemplate> emailTemplates) {
		this.emailTemplates = emailTemplates;
	}

	public IEmailTemplateService getEmailTemplateService() {
		return emailTemplateService;
	}

	public void setEmailTemplateService(IEmailTemplateService emailTemplateService) {
		this.emailTemplateService = emailTemplateService;
	}

	public EmailTemplateFilter getEmailTemplateFilter() {
		return emailTemplateFilter;
	}

	public void setEmailTemplateFilter(EmailTemplateFilter emailTemplateFilter) {
		this.emailTemplateFilter = emailTemplateFilter;
	}
	
}
